﻿/**************************************************************
 *
 * 唯一标识：a741b6b1-9ee6-4f46-85f4-b813b7979af2
 * 命名空间：Sgr.Generator.Segment.Sead
 * 创建时间：2024/6/20 22:18:58
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using Microsoft.Extensions.Logging;
using Sgr.Data;
using Sgr.Data.DatabaseTranslators;
using Sgr.Generator.Segment.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sgr.Generator.Segment.Sead
{
    /// <summary>
    /// 数据库初始化类，用于初始化基于标识的Id分段信息
    /// </summary>
    public class SegmentDataBaseInitialize : IDataBaseInitialize
    {
        private readonly ISegmentEntityDataStorage _segmentEntityDataStorage;
        private readonly IEnumerable<ISegmentProvider> _segmentProviders;
        private readonly ILogger<SegmentDataBaseInitialize> _logger;

        /// <summary>
        /// 初始化 <see cref="SegmentDataBaseInitialize"/> 类的新实例
        /// </summary>
        /// <param name="segmentEntityDataStorage">分段实体数据存储接口</param>
        /// <param name="segmentProviders">分段提供者集合</param>
        /// <param name="logger">日志记录器</param>
        public SegmentDataBaseInitialize(
            ISegmentEntityDataStorage segmentEntityDataStorage,
            IEnumerable<ISegmentProvider> segmentProviders,
            ILogger<SegmentDataBaseInitialize> logger)
        {
            _logger = logger;
            _segmentProviders = segmentProviders;
            _segmentEntityDataStorage = segmentEntityDataStorage;
        }

        /// <summary>
        /// 获取初始化顺序，默认值为90 （最先创建号段）
        /// </summary>
        public int Order => 90;

        /// <summary>
        /// 执行数据库初始化
        /// </summary>
        /// <returns>表示异步操作的任务</returns>
        public async Task Initialize()
        {
            await _segmentEntityDataStorage.CreateTableIfNotExist();

            var keys = await _segmentEntityDataStorage.GetIdsAsync();

            foreach (var provider in _segmentProviders)
            {
                var dic = provider.GetSegments();

                foreach (var item in dic)
                {
                    if (!keys.Contains(item.Key))
                    {
                        _logger.LogInformation($"Insert Segment : {item.Key}  ...");
                        if (!await _segmentEntityDataStorage.InsertAsync(item.Key, 2000, item.Value))
                            _logger.LogError($"Insert Segment : {item.Key} Fails !");
                    }
                }
            }
        }
    }
}